package org.business.accounting.components;

import java.util.Collection;
import java.util.Iterator;

import org.apache.tapestry5.annotations.Component;
import org.apache.tapestry5.annotations.Parameter;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.annotations.SetupRender;
import org.apache.tapestry5.corelib.components.Form;
import org.apache.tapestry5.corelib.components.PageLink;
import org.apache.tapestry5.corelib.components.PasswordField;
import org.apache.tapestry5.corelib.components.TextField;
import org.apache.tapestry5.ioc.Messages;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.business.accounting.beans.UserBean;
import org.business.accounting.interfaces.User;
import org.business.accounting.pages.Index;
import org.business.accounting.service.UserDAO;

@SuppressWarnings("unused")
public class LogIn {
	
	@Inject
	private UserDAO userDAO;
	
	@Inject
	private Messages messages;
	
	@Parameter(required = true)
	@Property
	private User currentUser;
	
	@Parameter(required = true)
	@Property
	private User tmpUser;
	
	@Component(parameters = {"page = Registration"})
	private PageLink toRegistration;
	
	@Component(parameters = {"value = tmpUser.userName"})
	private TextField userNameField;
	
	@Component(parameters = {"value = tmpUser.password"})
	private PasswordField passwordField;
	
	@Component
	private Form logInForm;
	
	//
	// Event handlers
	//
	
	@SetupRender
	void initialize() {
		tmpUser = new UserBean();
	}
	
	void onPrepare() {
		tmpUser = new UserBean();
	}
	
	Object onSubmit() {
		User user = userDAO.get(tmpUser.getUserName());
		if ( (user != null) && (user.getPassword().equalsIgnoreCase(tmpUser.getPassword())) ) {
			currentUser = user;
		} else {
			logInForm.recordError(userNameField,messages.get("user-dont-exist"));
		}
		
		return Index.class;
	}
}
